import 'dart:async';

import 'package:get/get.dart';

import '../../../../controller/network/bridge.dart';
import '../../../../controller/network/network_ctrl.dart';
import '../../../../model/bean/latest_analysis_bean.dart';
import '../../../../model/bean/latest_raw_data_bean.dart';
import 'lift_details_ctrl.dart';

class InfoCtrl extends LiftDetailsCtrl {
  final _ldCtrl = Get.find<LiftDetailsCtrl>();

  // 查看网络状态
  final _nc = Get.find<NetworkCtrl>();

  // 设备是否离线（默认离线状态）
  final RxInt offline = 1.obs;

  // 监控设备信息
  final latest = Rx<Latest>();

  // 电梯运行统计
  final latestAnalysis = Rx<LatestAnalysisBean>();

  // 存储定时器
  Timer cancelTimer = null;

  @override
  void onInit() {
    // 创建网络变化观察
    Bridget.createNetworkCtrl(this);

    // 定时执行
    // createTimer();
  }

  @override
  void onClose() {
    // 移除观察
    Bridget.delNetworkCtrl(this);

    // 取消定时
    if (cancelTimer != null) cancelTimer.cancel();
  }

  @override
  void modify() {
    if (_nc.networkStatus.value) {
      if (_ldCtrl.isActivateStatus.value) {
        createTimer();
      }
    } else {
      if (cancelTimer != null) cancelTimer.cancel();
    }
  }

  /// 合并请求
  void concurrentRequests() async {
    Future.wait([
      _ldCtrl.readLatestAnalysis(),
      _ldCtrl.readLatestRawData(),
    ]).then((value) {
      print("定时更新电梯运行状态：$value");
    });
  }

  /// 创建定时器
  void createTimer() {
    cancelTimer = Timer.periodic(Duration(seconds: 3), (timer) {
      if (_ldCtrl.isActivateStatus.value) {
        // print("执行了");
        concurrentRequests();
        return timer;
      }
    });
  }
}
